package com.wande.dataplatform.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.wande.common.core.domain.R;
import com.wande.common.core.validate.AddGroup;
import com.wande.common.core.validate.EditGroup;
import com.wande.common.excel.utils.ExcelUtil;
import com.wande.common.log.annotation.Log;
import com.wande.common.log.enums.BusinessType;
import com.wande.common.mybatis.core.page.PageQuery;
import com.wande.common.mybatis.core.page.TableDataInfo;
import com.wande.common.web.core.BaseController;
import com.wande.dataplatform.domain.bo.DataSourceBo;
import com.wande.dataplatform.domain.vo.DataSourceVo;
import com.wande.dataplatform.service.IDataSourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据源管理Controller
 *
 * @author ruoyi
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/dataplatform/datasource")
@Tag(name = "数据源管理", description = "数据源管理接口")
public class DataSourceController extends BaseController {

    private final IDataSourceService dataSourceService;

    /**
     * 查询数据源列表
     */
    @SaCheckPermission("dataplatform:datasource:list")
    @GetMapping("/list")
    @Operation(summary = "查询数据源列表", description = "分页查询数据源列表")
    public TableDataInfo<DataSourceVo> list(DataSourceBo bo, PageQuery pageQuery) {
        return dataSourceService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出数据源列表
     */
    @SaCheckPermission("dataplatform:datasource:export")
    @Log(title = "数据源管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @Operation(summary = "导出数据源列表", description = "导出数据源列表到Excel")
    public void export(DataSourceBo bo, HttpServletResponse response) {
        List<DataSourceVo> list = dataSourceService.queryList(bo);
        ExcelUtil.exportExcel(list, "数据源列表", DataSourceVo.class, response);
    }

    /**
     * 获取数据源详细信息
     *
     * @param id 数据源主键
     */
    @SaCheckPermission("dataplatform:datasource:query")
    @GetMapping("/{id}")
    @Operation(summary = "获取数据源详情", description = "根据ID获取数据源详细信息")
    @Parameter(name = "id", description = "数据源ID", required = true)
    public R<DataSourceVo> getInfo(@PathVariable Long id) {
        return R.ok(dataSourceService.queryById(id));
    }

    /**
     * 新增数据源
     */
    @SaCheckPermission("dataplatform:datasource:add")
    @Log(title = "数据源管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Operation(summary = "新增数据源", description = "创建新的数据源")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DataSourceBo bo) {
        if (!dataSourceService.checkNameUnique(bo)) {
            return R.fail("新增数据源'" + bo.getName() + "'失败，数据源名称已存在");
        }
        boolean result = dataSourceService.insertByBo(bo);
        return toAjax(result);
    }

    /**
     * 修改数据源
     */
    @SaCheckPermission("dataplatform:datasource:edit")
    @Log(title = "数据源管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Operation(summary = "修改数据源", description = "更新数据源信息")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DataSourceBo bo) {
        if (!dataSourceService.checkNameUnique(bo)) {
            return R.fail("修改数据源'" + bo.getName() + "'失败，数据源名称已存在");
        }
        boolean result = dataSourceService.updateByBo(bo);
        return toAjax(result);
    }

    /**
     * 删除数据源
     *
     * @param ids 数据源主键串
     */
    @SaCheckPermission("dataplatform:datasource:remove")
    @Log(title = "数据源管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除数据源", description = "批量删除数据源")
    @Parameter(name = "ids", description = "数据源ID数组", required = true)
    public R<Void> remove(@PathVariable Long[] ids) {
        boolean result = dataSourceService.deleteWithValidByIds(List.of(ids));
        return toAjax(result);
    }

    /**
     * 测试数据源连接
     *
     * @param id 数据源主键
     */
    @SaCheckPermission("dataplatform:datasource:test")
    @Log(title = "数据源管理", businessType = BusinessType.OTHER)
    @PostMapping("/test/{id}")
    @Operation(summary = "测试数据源连接", description = "测试指定数据源的连接是否正常")
    @Parameter(name = "id", description = "数据源ID", required = true)
    public R<Void> testConnection(@PathVariable Long id) {
        boolean result = dataSourceService.testConnection(id);
        if (result) {
            return R.ok("连接测试成功");
        } else {
            return R.fail("连接测试失败");
        }
    }

    /**
     * 测试数据源连接（使用BO对象）
     */
    @SaCheckPermission("dataplatform:datasource:test")
    @Log(title = "数据源管理", businessType = BusinessType.OTHER)
    @PostMapping("/testConnection")
    @Operation(summary = "测试数据源连接", description = "测试数据源连接（不保存）")
    public R<Void> testConnectionByBo(@RequestBody DataSourceBo bo) {
        boolean result = dataSourceService.testConnectionByBo(bo);
        if (result) {
            return R.ok("连接测试成功");
        } else {
            return R.fail("连接测试失败");
        }
    }

}
